package com.cskaoyan.mall.search.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.dto.AllItemResponse;
import com.cskaoyan.mall.dto.ItemDto;
import com.cskaoyan.mall.search.api.ProductApi;
import com.cskaoyan.mall.search.consts.SearchRetCode;
import com.cskaoyan.mall.search.converter.ProductConverter;
import com.cskaoyan.mall.search.entity.ItemDocument;
import com.cskaoyan.mall.search.entity.ItemDocumentStandardText;
import com.cskaoyan.mall.search.exception.SearchException;
import com.cskaoyan.mall.search.repository.Product2Repository;
import com.cskaoyan.mall.search.repository.ProductRepository;
import com.cskaoyan.mall.search.service.InitDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LY
 * @since 2022/06/26 20:49
 */
@Slf4j
@Service
public class InitDataServiceImpl implements InitDataService {

    @Autowired
    ProductApi productApi;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    Product2Repository product2Repository;

    @Autowired
    ProductConverter productConverter;

    @Override
    public void initItems() {


        try {
            AllItemResponse allProductItem = productApi.getAllProductItem();
            if(!SearchRetCode.SUCCESS.getCode().equals(allProductItem.getCode())){
                throw new SearchException(SearchRetCode.FAILED.getCode(), "获取商品详情失败");
            }

            List<ItemDto> items = allProductItem.getAllItems();

            List<ItemDocument> itemDocuments = productConverter.items2Documents(items);

            List<ItemDocumentStandardText> itemDocumentStandardTexts = productConverter.items2DocumentStandards(items);

            productRepository.saveAll(itemDocuments);
            product2Repository.saveAll(itemDocumentStandardTexts);
        }catch (Exception e){
            log.error("InitDataServiceImpl.initItems Occur Exception :" + e);
            e.printStackTrace();
        }

    }
}
